package com.three.service.impl;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.three.dao.ClazzDao;
import com.three.dao.CrollcallDao;
import com.three.dao.SRrecordDao;
import com.three.dao.SrollcallDao;
import com.three.entity.SRrecord;
import com.three.entity.Srollcall;
import com.three.service.SrollcallService;
import com.three.util.Constant;

@Service
public class SrollcallServiceImpl implements SrollcallService {

	@Autowired
	SrollcallDao srollcallDao;
	@Autowired
	CrollcallDao crollcallDao;
	@Autowired
	SRrecordDao sRrecordDao;
	@Autowired
	ClazzDao clazzDao;
	
	@Override
	public Srollcall findSrollcallByUcid(Integer uid, Integer cid) {
		List<Integer> ucids = clazzDao.findUcidByUidWithCid(uid, cid);
		return srollcallDao.findSrollcallByUcid(ucids.get(0));
	}

	@Override
	public String sign(Integer uid, Integer cid, String rollcallCode) {
		String result = null;
		String rc = clazzDao.findRollcallCodeByCid(cid);
		if (rc.equals(rollcallCode)) {
			//邀请码匹配
			List<Integer> ucids = clazzDao.findUcidByUidWithCid(uid, cid);
			int ucid = ucids.get(0);
			srollcallDao.updateMiss(ucid,
					srollcallDao.findMissByUcid(ucid)-1);
			srollcallDao.updateAttendance(ucid,
					srollcallDao.findAttendanceByUcid(ucid)+1);
			List<SRrecord> sRrecords = sRrecordDao.findSRrecords(ucid);
			int id = sRrecords.get(0).getId();
			sRrecordDao.updateSRrecord(id,Constant.ATTENDANCE);
			result = "success";
		}else{
			//邀请码不匹配
			if ("stopped".equals(rc)) {
				result = "stopped";
			}else{				
				result="notmatch";
			}
		}
		return result;
	}

	@Override
	public String updateRollcallState(Integer cid, String rollcallName,
			Integer ucid, Integer oStatus, Integer uStatus) {
		String result = null;
		String oStatusName = getStatusName(oStatus);
		String uStatusName = getStatusName(uStatus);
		HashMap<String, Object> hashmap = new HashMap<String, Object>();
		hashmap.put("cid", cid);
		hashmap.put("ucid", ucid);
		hashmap.put("rollcallName", rollcallName);
		hashmap.put("oStatusName", oStatusName);
		hashmap.put("uStatusName", uStatusName);
		crollcallDao.updateCrollcallState(hashmap);
		srollcallDao.updateSrollcallState(hashmap);
		List<SRrecord> sRrecords = sRrecordDao.findSRrecords(ucid);
		sRrecordDao.updateSRrecord(
				sRrecords.get(0).getId(), uStatus);
		result = "success";
		return result;
	}
	
	private String getStatusName(Integer status){
		String statusName = null;
		if (status == Constant.ATTENDANCE) {
			statusName = "attendance";
		}else if(status == Constant.DELAY){
			statusName = "delay";
		}else if(status == Constant.MISS){
			statusName = "miss";
		}else if(status == Constant.LEAVE){
			statusName = "`leave`";
		}
		return statusName;
	}

}
